//
//  ESPBLU_ViewController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2022/1/13.
//  Copyright © 2022 Chun Hung Cheung. All rights reserved.
//

#import "VL4BLUViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "ESPFBYBLEHelper.h"
#import "ESPDataConversion.h"
#import "BindSuccessViewController.h"
#import "YKTipsView.h"
#import "BlufiClient.h"
#import "YKWiFiListVController.h"

/*V2*/
#import "AppDelegate.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import "GCDAsyncSocket.h"
#import "FBWifiIModel.h"
#import <iconv.h>

@interface VL4BLUViewController ()<CBCentralManagerDelegate, CBPeripheralDelegate, BlufiDelegate,BindSuccessViewControllerDelegate,YKLowBatteryViewDelegate,UITextFieldDelegate,GCDAsyncSocketDelegate>
@property(nonatomic, copy)  NSMutableArray<ESPPeripheral *> *peripheralArray;
@property(nonatomic, strong) ESPFBYBLEHelper *espFBYBleHelper;
@property(nonatomic, copy) NSString *filterContent;

@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic,strong) dispatch_source_t wait_timer;
@property (nonatomic,strong) YKTipsView *lowView;
@property (nonatomic,strong) YKTipsView *failView;
//蓝牙连接
@property(strong, nonatomic)BlufiClient *blufiClient;
@property(assign, atomic)BOOL connected;
@property(copy,nonatomic)NSString *devicesid;
@property (nonatomic,strong) UIAlertController *alertController;
@property(nonatomic,strong)UILabel *selectedWiflLabel;
@property(nonatomic,strong)UITextField *wifi_Name_TextField;
@property(nonatomic,strong)UITextField *wifi_password_TextField;
@property(nonatomic,strong)UIButton *nextButton;


// AP方式
@property(nonatomic,strong)GCDAsyncSocket *clientSocket;
@property(nonatomic,strong)NSArray *wifi_array;
@property(nonatomic,assign)bool showSucessView;
//计数
@property(nonatomic,assign)int  postBluMessage;

@property(nonatomic,strong)NSData *post_data;
@property (nonatomic,strong)ESPPeripheral *blu_devies;
@end

@implementation VL4BLUViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setup];
   
     self.view.backgroundColor = [UIColor whiteColor];

    if(!self.is_Search){
        if (self.bind_way == 1) {
            
            __weak VL4BLUViewController *weakSelf = self;
            self.espFBYBleHelper = [ESPFBYBLEHelper share];
            self.espFBYBleHelper.bleScanSuccessBlockStatus = ^(CBManagerState status) {
           
                NSLog(@"status-->%ld",(long)status);
                if (status == CBManagerStatePoweredOn) {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        if (weakSelf.alertController) {
                           [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                        }
                        
                        [SVProgressHUD showWithStatus:NSLocalizedString(@"扫描WiFi中...", nil)];
                    }];
                }else if(status == CBManagerStateUnauthorized){
                    
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        if (weakSelf.alertController) {
                           [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                        }
                        weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"APP蓝牙权限未开启，绑定智能锁需要开启蓝牙权限，请前往系统设置里找到APP打开蓝牙权限", nil) preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"去设置", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                          [weakSelf.navigationController popViewControllerAnimated:YES];
                            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                          [[UIApplication sharedApplication] openURL:url];
                        }];
                        [weakSelf.alertController addAction:deleteButton];
                        [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
                    }];
                }else if(status == CBManagerStatePoweredOff){
                    
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        if (weakSelf.alertController) {
                           [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                        }
                        weakSelf.alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Note", nil) message:NSLocalizedString(@"手机蓝牙功能未打开，绑定智能锁时需要请打开手机的蓝牙功能", nil) preferredStyle:UIAlertControllerStyleAlert];
                        UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [weakSelf.navigationController popViewControllerAnimated:YES];
                        }];
                        [weakSelf.alertController addAction:deleteButton];
                        [weakSelf presentViewController:weakSelf.alertController animated:YES completion:nil];
                    }];
                }
            };

            self.filterContent = [ESPDataConversion loadBlufiScanFilter];
           
           //开始扫描设备
           [self scanDeviceInfo];
            
        }else{
            
            __weak VL4BLUViewController *weakSelf = self;
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (weakSelf.alertController) {
                   [weakSelf.alertController dismissViewControllerAnimated:YES completion:nil];
                }
                [SVProgressHUD showWithStatus:NSLocalizedString(@"扫描WiFi中...", nil)];
                
                
                [self sendAP];
            }];
            
        }
    }else{
        [SVProgressHUD showWithStatus:NSLocalizedString(@"扫描WiFi中...", nil)];
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AddNewDeviceResponse" object:nil];
    
    //新接口绑定设备回复消息第一步
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(AddNewRecvSocketMessage:) name:@"AddNewDeviceResponse" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addNewDevicesResponse" object:nil];
    //监听 添加新的设备请求，监听收到回复的信息 的通知 新接口绑定设备回复消息第二步
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addNewDevicesResponse:) name:@"addNewDevicesResponse" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addNewDevices" object:nil];
    
    //监听 添加新设备的回应 通知 绑定设备成功  通知监听 跳转到完成界面，获取设备列表
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RecvSocketMessage:) name:@"addNewDevices" object:nil];
}


- (void)setup
{
     self.title = NSLocalizedString(@"设置网络", nil);
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,80,40);
     backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"返回", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"button_back_lightgray_arrow"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftAction) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];

  
     self.selectedWiflLabel.text = NSLocalizedString(@"Select WiFi", nil);
     self.wifi_Name_TextField.placeholder = NSLocalizedString(@"选择Wi-Fi", nil);
     self.wifi_password_TextField.placeholder = NSLocalizedString(@"请输入WIFI密码", nil);
    [self.nextButton setTitle:NSLocalizedString(@"下一步", nil) forState:UIControlStateNormal];
     self.nextButton.backgroundColor = [UIColor orangeColor];
    [self.nextButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FFFFFF"] forState:UIControlStateNormal];
  
}

- (void)selectLeftAction
{
    
     self.wifi_array = [NSArray array];
    [self removeTimer];
    [self.navigationController popViewControllerAnimated:YES];
    
    if (self.bind_way == 1){
      [self.espFBYBleHelper stopScan];
       self.espFBYBleHelper = nil;
    }
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    if (_timer) {
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
    __block int timeout = 30;
    __weak VL4BLUViewController *weakSelf = self;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
       
        timeout--;
        NSLog(@"scan WiFi timeout-->%d",timeout);
        
        if(timeout == 10 && !self.connected){
            NSLog(@"connect device again");
           [weakSelf.blufiClient connect:weakSelf.blu_devies.uuid.UUIDString];
        }
        
        if (timeout <= 0) {
           
            if (_timer) {
               dispatch_source_cancel(_timer);
               _timer = nil;
            }
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (self.bind_way == 1){
                   [self.espFBYBleHelper stopScan];
                    self.espFBYBleHelper = nil;
                }
                
                if(self.wifi_array.count == 0){
                  if([SVProgressHUD isVisible]){
                     [SVProgressHUD dismiss];
                   }
                  [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"扫描WiFi失败，请重新触发设备进入配网模式", nil) duration:3];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self.navigationController popViewControllerAnimated:YES];
                    });
                }
            }];
        }
    });
    dispatch_resume(_timer);
    
}

#pragma mark BindSuccessViewControllerDelegate
- (void)didSeenewMydeviceBtnClick
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeArea" object:nil];
    [self.navigationController popToRootViewControllerAnimated:YES];
   
}


// 展示安全密码设置界面
- (void)showSetPsd
{
    self.lowView = [[YKTipsView alloc]initWithSetSercurityPsd:NSLocalizedString(@"设置安全密码", nil) andSubTitle:NSLocalizedString(@"请设置安全密码，用于App远程开锁", nil) iconName:@"vl0_psd_top_popup" type:1 deviceBid:self.devicesid isView:NO];
     self.lowView.delegate = self;
    [[UIApplication sharedApplication].keyWindow addSubview:self.lowView];
    [self.lowView show];
}

- (void)sercurityCode:(NSString *)code type:(int)type
{
    [SVProgressHUD show];
    NSURL *url = [YKBusinessFramework eques_set_vl0_psd];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    if (self.devicesid) {
        [dict setValue:self.devicesid forKey:@"deviceId"];
    }
    [dict setValue:code forKey:@"pwd"];
    [AFNHTTPSRequest httpsPostRequestWithUrl:url errorHint:^(id errorData) {
        [SVProgressHUD dismiss];
         NSLog(@"设置安全密码错误-->%@",errorData);
        //[SVProgressHUD showErrorWithStatus:@"服务异常！"];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } deleteDic:dict isFavorite:YES result:^(id data) {
        [SVProgressHUD dismiss];
        if ([[data objectForKey:@"code"] intValue] == 0) {
            [self dissMissLowBattery];
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"设置成功", nil)];
            FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(self.devicesid)]] firstObject];
            if (list) {
                 list.sercurityStatus = YES;
                 list.sercurityCode = code;
                [list bg_saveOrUpdate];
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissBind" object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeArea" object:nil];
            
            [self.navigationController popToRootViewControllerAnimated:YES];

        }else if([[data objectForKey:@"code"] intValue] == 4407){
            [self dissMissLowBattery];
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"已设置安全密码，重复设置", nil)];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissBind" object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeArea" object:nil];
            
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else if ([[data objectForKey:@"code"] intValue] == 4008){
            [self dissMissLowBattery];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"dismissBind" object:nil];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeArea" object:nil];
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
        else if([[data objectForKey:@"code"] intValue] == 4634){
            [self dissMissLowBattery];
            
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备与账号绑定关系异常", nil)];
            
        }else{
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设置失败，请重新设置", nil)];
        }
    }];
}

- (void)dissMissLowBattery
{
      if (self.lowView) {
        [self.lowView removeFromSuperview];
         self.lowView = nil;
     }
    
    if (self.failView) {
      [self.failView removeFromSuperview];
       self.failView = nil;
    }
}



- (void)scanDeviceInfo {
     NSLog(@"start search blu devices");
    [self.espFBYBleHelper startScan:^(ESPPeripheral * _Nonnull device) {
        NSLog(@"blu search device.uuid-->%@",device.uuid);
        if ([self shouldAddToSource:device]) {
            [self.espFBYBleHelper stopScan];
             NSLog(@"device.uuid-->%@",device.uuid);
             NSLog(@"device.name-->%@",device.name);
            [self connect:device];
        }
    }];
}

- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    if (self.bind_way == 1){
      [self.espFBYBleHelper stopScan];
       self.espFBYBleHelper = nil;
    }
    
    if([SVProgressHUD isVisible]){
       [SVProgressHUD dismiss];
    }
}

- (BOOL)shouldAddToSource:(ESPPeripheral *)device {
    // Check filter
    if(self.is_support_screen && self.lock_id.length >0){
        if([device.name hasPrefix:@"SPLIT"]){
            return YES;
        }else{
            return NO;
        }
    }else{
        if (_filterContent && _filterContent.length > 0) {
            if (!device.name || ![device.name hasPrefix:_filterContent]) {
                // The device name has no filter prefix
                return NO;
            }
        }
        return YES;
    }
}


// 去连接
- (void)connect:(ESPPeripheral*)device {
    
     if (_blufiClient) {
        [_blufiClient close];
         _blufiClient = nil;
      }
    
       _blufiClient = [[BlufiClient alloc] init];
       if(self.is_Search){
        _blufiClient.isVL2 = ([device.name containsString:@"VL2"]) ? YES : NO;
       }else{
        _blufiClient.isVL2 = (self.devicetype == EQUESVL2) ? YES : NO;
       }
      _blufiClient.centralManagerDelete = self;
      _blufiClient.peripheralDelegate = self;
      _blufiClient.blufiDelegate = self;
       self.blu_devies = device;
     [_blufiClient connect:device.uuid.UUIDString];
}


#pragma mark centralManagerDelete
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
}

- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    
    NSLog(@"Connected device \n");
    self.connected = YES;

    
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"Connet device failed \n");
    self.connected = NO;
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    [self onDisconnected];
     NSLog(@"Disconnected device \n");
     self.connected = NO;
}

- (void)onDisconnected {
    if (_blufiClient) {
       [_blufiClient close];
    }
}


//蓝牙连好 可以发送数据等操作
- (void)blufi:(BlufiClient *)client gattPrepared:(BlufiStatusCode)status service:(CBService *)service writeChar:(CBCharacteristic *)writeChar notifyChar:(CBCharacteristic *)notifyChar {
    NSLog(@"Blufi gattPrepared status:%d", status);
    if (status == StatusSuccess) {
         self.connected = YES;
         NSLog(@"BluFi connection has prepared \n");
        
        NSString *cusData = [NSString stringWithFormat:@"{\"method\":\"wifilist\"}"];
        NSData *data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
       [self.blufiClient postCustomData:data];
    
    } else {
        [self onDisconnected];
        if (!service) {
            NSLog(@"Discover service failed");
        } else if (!writeChar) {
            NSLog(@"Discover write char failed");
        } else if (!notifyChar) {
            NSLog(@"Discover notify char failed");
        }
    }
}

- (void)blufi:(BlufiClient *)client didNegotiateSecurity:(BlufiStatusCode)status {
    NSLog(@"Blufi didNegotiateSecurity %d", status);
    if (status == StatusSuccess) {
        NSLog(@"Negotiate security complete");
    } else {
        NSLog(@"Negotiate security failed: %d",status);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceVersionResponse:(BlufiVersionResponse *)response status:(BlufiStatusCode)status {

    if (status == StatusSuccess) {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device version: %@",response.getVersionString]);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device version error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didPostConfigureParams:(BlufiStatusCode)status {
    if (status == StatusSuccess) {
        NSLog(@"Post configure params complete");
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Post configure params failed: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceStatusResponse:(BlufiStatusResponse *)response status:(BlufiStatusCode)status {
  
    if (status == StatusSuccess) {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device status:\n%@", response.getStatusInfo]);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device status error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveDeviceScanResponse:(NSArray<BlufiScanResponse *> *)scanResults status:(BlufiStatusCode)status {
  
    if (status == StatusSuccess) {
        NSMutableString *info = [[NSMutableString alloc] init];
        [info appendString:@"Receive device scan results:\n"];
        for (BlufiScanResponse *response in scanResults) {
            [info appendFormat:@"SSID: %@, RSSI: %d\n", response.ssid, response.rssi];
        }
        NSLog(@"%@",info);
    } else {
        NSLog(@"%@",[NSString stringWithFormat:@"Receive device scan results error: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didPostCustomData:(nonnull NSData *)data status:(BlufiStatusCode)status {
    if (status == StatusSuccess) {
         NSLog(@"发送自定义数据成功Post custom data complete \n");
        // 发送数据成功
    } else {
         NSLog(@"%@",[NSString stringWithFormat:@"Post custom data failed: %d", status]);
    }
}

- (void)blufi:(BlufiClient *)client didReceiveCustomData:(NSData *)data status:(BlufiStatusCode)status {
    NSString *customString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",[NSString stringWithFormat:@"Receive device custom data: %@", customString]);
    
    if (!customString) {
         customString = [[NSMutableString alloc]initWithData:[self cleanUTF8:data] encoding:NSUTF8StringEncoding];
         NSLog(@"cleanUTF8 str2-->%@ \n",customString);
    }
    
    
    if (!customString) {
         customString = [self convertedToUtf8String:data];
         NSLog(@"convertedToUtf8String str2-->%@ \n",customString);
    }
    
    
    
    NSDictionary *dict  = [Tooles jsonAnalysis:customString];
    NSLog(@"jsonAnalysis after-->%@",dict);
    
    /*
     {
       2022-12-27 18:06:19.523869+0800 DoorBell[27115:10898700] str-->start
       2022-12-27 18:06:19.527188+0800 DoorBell[27115:10898700] str-->{"count":21,"list":"[{\"ssid\":\"LINK_test\",\"rssi\":-34},{\"ssid\":\"DIRECT-g5DESKTOP-155OPPHmsOR\",\"rssi\":-35},{\"ssid\":\"Banker-WiFi\",\"rssi\":-36},{\"ssid\":\"999\",\"rssi\":-39},{\"ssid\":\"EQUES_UniFi\",\"rssi\":-44},{\"ssid\":\"HW破网!@#￥%*2.4G\",\"rssi\":-46},{\"ssid\":\"lynlyn007\",\"rssi\":-46},{\"ssid\":\"TP-LINK_D5EE\",\"rssi\":-48},{\"ssid\":\"device-test\",\"rssi\":-49},{\"ssid\":\"yikang移康研发01\",\"rssi\":-50},{\"ssid\":\"ChinaNet-3m2z\",\"rssi\":-52},{\"ssid\":\"TP-LINK_2B07\,\"rssi\":-52},{\"ssid\":\"ChinaNet-39EP\",\"rssi\":-55},{\"ssid\":\"ps\",\"rssi\":-57},{\"ssid\":\"eques-home\",\"rssi\":-57},{\"ssid\":\"MONA\",\"rssi\":-63},{\"ssid\":\"DIRECT-CC-HP Laser 178nw\",\"rssi\":-65},{\"ssid\":\"UPGRADE-AP\",\"rssi\":-65},{\"ssid\":\"test007\",\"rssi\":-68},{\"ssid\":\"CU_rB2P\",\"rssi\":-71},{\"ssid\":\"MERCURY_76A6\",\"rssi\":-59}]"}
        2022-12-27 18:06:19.530486+0800 DoorBell[27115:10898700] str-->end
     
     */
      
    if([customString containsString:@"eques_wifi_config"]){
        
       NSLog(@"绑定结果receive-- %@",customString);
        
     //{"eques_wifi_config":{"describe":"e55bd61707105650205b02f004a254c5","status":0}}
        
        
       NSDictionary *dict = [Tooles jsonAnalysis:customString];
        /*
            Status（值 int 类型） Describe（string 类型）0 对应绑定成功的 32 位 bid
            1 未找到 WiFi
            2 WiFi 密码错误
            3 设备获取路由 IP 错误
            4 设备无法连接 WiFi
            5 设备登录失败
            6 设备绑定失败
            7 设备连接服务器失败
        */
        
        if([SVProgressHUD isVisible]){
           [SVProgressHUD dismiss];
        }
        
        if (_wait_timer) {
           dispatch_source_cancel(_wait_timer);
            _wait_timer = nil;
        }
        
        
        
        NSDictionary *dict2 = [dict objectForKey:@"eques_wifi_config"];
        int code = [[dict2 objectForKey:@"status"] intValue];
        NSString *title;
        NSString *subtitle;
        
        switch (code) {
                
            case 0:
            {
                if(!self.devicesid){
                    [YKBusinessFramework equesGetDeviceList];
                     self.devicesid = [dict2 objectForKey:@"describe"];
                    [self removeTimer];
                
                    NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
                    
                    if(modelArray.count > 0){
                         FBWifiIModel *model = [modelArray firstObject];
                         model.wifiPasswordName = self.wifi_password_TextField.text;
                        [model bg_saveOrUpdate];
                    }else{
                         FBWifiIModel *model = [[FBWifiIModel alloc]init];
                         model.wifiName = self.wifi_Name_TextField.text;
                         model.wifiPasswordName = self.wifi_password_TextField.text;
                        [model bg_save];
                    }
                    
                     BindSuccessViewController *vc = [[BindSuccessViewController alloc]init];
                     vc.delegate = self;
                    if(self.is_support_screen && self.lock_id.length > 0){
                         vc.optionstr = @"Cat";
                    }else{
                        vc.optionstr = @"VL0";
                    }
                     vc.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self.view.window.rootViewController presentViewController:vc animated:YES completion:^{
                        [self showSetPsd];
                    }];
                }
                
            }
                break;
                
            case 1:
            {
                
             title = NSLocalizedString(@"WiFi not found", nil);
             subtitle = NSLocalizedString(@"WiFi signal is bad, please enter correct WiFi name", nil);
            }
                break;
                
            case 2:
            {
                title = NSLocalizedString(@"WiFi password error", nil);
                subtitle = NSLocalizedString(@"Please enter the correct WiFi password", nil);
            }
                break;
            case 3:
            {
                title = NSLocalizedString(@"Device get route IP error", nil);
                subtitle = NSLocalizedString(@"WiFi connection error or device cannot connect to WiFi, please restart the router to try", nil);
                
            }
                break;
            case 4:
            {
                title = NSLocalizedString(@"The device cannot connect to WiFi", nil);
                subtitle = NSLocalizedString(@"Other exceptions encountered when connecting to WiFi, please restart the router to try", nil);
            }
                break;
            case 5:
            {
                title = NSLocalizedString(@"Device login failed", nil);;
                subtitle = @"";
            }
                break;
            case 6:
            {
                title = NSLocalizedString(@"Device binding failed", nil);
                subtitle = @"";
            }
                break;
            case 7:
            {
                title = NSLocalizedString(@"The device failed to connect to the server", nil);
                subtitle = NSLocalizedString(@"WiFi cannot connect to the internet. Please make sure WiFi can connect to the internet", nil);
            }
                break;
            default:
                break;
        }
    
       
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
            if(code != 0){
                self.failView = [[YKTipsView alloc]initwithTitle:title subtitle:subtitle];
                self.failView.delegate = self;
               [[UIApplication sharedApplication].keyWindow addSubview:self.failView];
               [self.failView show];
            }
        });
        
        return;
    }
    
    if([[dict objectForKey:@"count"] intValue] == 0){
        
        self.postBluMessage ++;
        if(self.postBluMessage == 1){
            
            if([SERVER_ADDRS isEqualToString:@"testdistribute.ecamzone.cc"]){
               
                 NSString *cusData = [NSString stringWithFormat:@"{\"method\":\"wifilist\"}"];
                 NSData *data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                [self.blufiClient postCustomData:data];

            }else{
                
                 NSString *cusData = [NSString stringWithFormat:@"{\"method\":\"wifilist\"}"];
                 NSData *data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                [self.blufiClient postCustomData:data];
            
            }
            return;
        }else{
            [SVProgressHUD showErrorWithStatus:@"设备搜索WiFi列表返回为空，请重新扫描设备屏幕二维码！" duration:3];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
            return;
        }
    }
    
    
    if([[dict objectForKey:@"count"] intValue] > 0){
        
        NSArray *strarray;
        if([customString containsString:@"\"[{"] && [customString containsString:@"}]\""]){
        
            NSString *no_format_str  = [dict objectForKey:@"list"];
            NSString *str1 = [no_format_str stringByReplacingOccurrencesOfString:@"[" withString:@""];
            NSString *str3 = [str1 stringByReplacingOccurrencesOfString:@"]" withString:@""];
            NSArray *Arrat = [str3 componentsSeparatedByString:@","];

            NSMutableArray *array = [NSMutableArray array];
            
            if(Arrat.count % 2 == 0 && Arrat.count > 0){
                for (int i = 1; i <= Arrat.count; i ++) {
                    if(i % 2 == 0){
                        NSString *str = [NSString stringWithFormat:@"%@,%@",Arrat[i-2],Arrat[i-1]];
                        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
                        [array addObject:responseJSON];
                    }
                }
                strarray = [NSArray arrayWithArray:array];
            }
        }else{
            strarray = [dict objectForKey:@"list"];
        }

        if(strarray.count){
            
            if (_timer) {
               dispatch_source_cancel(_timer);
                _timer = nil;
            }
            
            
            // 创建一个NSSortDescriptor对象，指定要排序的key为"age"
            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rssi" ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSNumber *number1 = [NSNumber numberWithInteger:labs([(NSNumber *)obj1 integerValue])];
                NSNumber *number2 = [NSNumber numberWithInteger:labs([(NSNumber *)obj2 integerValue])];
                return [number1 compare:number2];
            }];

            // 使用sortDescriptor对数组进行排序
            NSArray *sortedArray = [strarray sortedArrayUsingDescriptors:@[sortDescriptor]];
            
            
             NSLog(@"dict2Wi-Fi-->%@",sortedArray);
            
             self.wifi_array = [NSArray arrayWithArray:sortedArray];
            
            [SVProgressHUD dismiss];
            
            YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
            self.definesPresentationContext = YES;
            wifilist.wifiarray = [NSArray arrayWithArray:sortedArray];
            wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
            wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
                NSLog(@"选中返回的Wi-Fi-->%@",wifi);
                
                self.wifi_Name_TextField.text = wifi;
                
                NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
                if(modelArray.count > 0){
                     FBWifiIModel *model = [modelArray firstObject];
                    if(model.wifiPasswordName.length > 0){
                      self.wifi_password_TextField.text = model.wifiPasswordName;
                    }
                }
        
            };
           [self.navigationController presentViewController:wifilist animated:YES completion:nil];
            
        }
    }
}

//新接口绑定设备回复消息第一步
- (void)AddNewRecvSocketMessage:(NSNotification *)notification
{
    NSDictionary *recvMsg = [notification object];
    NSString *reqid = [recvMsg objectForKey:@"reqid"];
    NSLog(@"AddNewDeviceResponserecvMsg = %@",recvMsg);
    NSDictionary *extra = [recvMsg objectForKey:@"extra"];
    NSLog(@"extraResponserecvMsg = %@",extra);
    if (extra == NULL)
    {
         //向服务器发送回复，允许添加
        [YKBusinessFramework equesAckAddResponse:reqid allow:allowAdd];
    }
}

//新接口绑定设备回复消息第二步
- (void)addNewDevicesResponse:(NSNotification *)notification
{
    
     if(self.devicesid.length > 0){
      NSLog(@"revice get bind sucess message");
      return;
    }
    
    if(self.showSucessView){
        return;
    }
    
    
    [UIApplication sharedApplication].idleTimerDisabled = NO;
    
    NSDictionary *dict = [notification object];
    NSString *bid = [dict objectForKey:@"bid"];
    if (bid.length > 0) {
        self.devicesid = bid;
    }else{
        NSDictionary *new_dict = [dict objectForKey:@"added_bdy"];
        NSString *bid = [new_dict objectForKey:@"bid"];
        self.devicesid = bid;
    }
    
    [SVProgressHUD dismiss];
     NSDictionary *recvMsg = [notification object];
     NSLog(@"addNewDevicesResponse = %@",recvMsg);
     self.wifi_array = nil;
    if ([[[notification object] objectForKey:@"code"] intValue] == 4000)
    {
       
        [self removeTimer];
 
        NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
        
        if(modelArray.count > 0){
             FBWifiIModel *model = [modelArray firstObject];
             model.wifiPasswordName = self.wifi_password_TextField.text;
            [model bg_saveOrUpdate];
        }else{
             FBWifiIModel *model = [[FBWifiIModel alloc]init];
             model.wifiName = self.wifi_Name_TextField.text;
             model.wifiPasswordName = self.wifi_password_TextField.text;
            [model bg_save];
        }
        
        
         BindSuccessViewController *vc = [[BindSuccessViewController alloc]init];
         vc.delegate = self;
         if(self.is_support_screen && self.lock_id.length > 0){
             vc.optionstr = @"Cat";
         }else{
             vc.optionstr = @"VL0";
         }

         vc.modalPresentationStyle = UIModalPresentationFullScreen;
        [self.view.window.rootViewController presentViewController:vc animated:YES completion:^{
            [self showSetPsd];
        }];
    }
    else if ([[[notification object] objectForKey:@"code"] intValue] == 4407)
    {
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"设备已经被绑定,勿需重复绑定", nil) duration:2];
        [self removeTimer];
        
    }else if ([[[notification object] objectForKey:@"code"] intValue] == 4429){
        
         [self removeTimer];
        
    }
}


- (void)removeTimer {
    
    if (_timer) {
       dispatch_source_cancel(_timer);
       _timer = nil;
    }
    
    if (_wait_timer) {
       dispatch_source_cancel(_wait_timer);
        _wait_timer = nil;
    }

}

//绑定设备成功 通知监听
- (void)RecvSocketMessage:(NSNotification *)notification
{
    [self removeTimer];
}



#pragma mark 密码输入框等控件

//文案显示
-(UILabel*)selectedWiflLabel
{
     if (!_selectedWiflLabel) {
         _selectedWiflLabel = [[UILabel alloc]init];
         _selectedWiflLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:28.0];
         _selectedWiflLabel.numberOfLines = 0;
         _selectedWiflLabel.textAlignment = NSTextAlignmentLeft;
        [_selectedWiflLabel sizeToFit];
         _selectedWiflLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
        [self.view addSubview:_selectedWiflLabel];
        [_selectedWiflLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationBarHeight]);
            make.left.equalTo(self.view.mas_left).offset(28);
        }];
    }
    return _selectedWiflLabel;
}


-(UITextField*)wifi_Name_TextField
{

    if (!_wifi_Name_TextField) {
        _wifi_Name_TextField = [[UITextField alloc]init];
        _wifi_Name_TextField.delegate = self;
        _wifi_Name_TextField.borderStyle = UITextBorderStyleNone;
        _wifi_Name_TextField.textColor = [UIColor blackColor];
        _wifi_Name_TextField.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
        _wifi_Name_TextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _wifi_Name_TextField.tag = 1234;
        NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"请输入WiFi名称", nil) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:16]}];
                 _wifi_Name_TextField.attributedPlaceholder = placeholderString;
    
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"vl0_form_switch"] forState:UIControlStateNormal];
        _wifi_Name_TextField.rightViewMode = UITextFieldViewModeAlways;
        _wifi_Name_TextField.rightView = btn;
        
        [self.view addSubview:_wifi_Name_TextField];
        [_wifi_Name_TextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(28);
            make.right.equalTo(self.view.mas_right).offset(-28);
            make.top.equalTo(self.selectedWiflLabel.mas_bottom).offset(60);
            make.height.mas_equalTo(44);
        }];

    }
    return _wifi_Name_TextField;

}


-(void)btnClick:(UIButton*)sender
{
    [self.view endEditing:YES];
    
    if(self.wifi_array.count > 0){
        
        YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
        self.definesPresentationContext = YES;
        wifilist.wifiarray = [NSArray arrayWithArray:self.wifi_array];
        wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
        wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
        wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
            NSLog(@"选中返回的Wi-Fi-->%@",wifi);
            
            self.wifi_Name_TextField.text = wifi;

            NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
            if(modelArray.count > 0){
                 FBWifiIModel *model = [modelArray firstObject];
                if(model.wifiPasswordName.length > 0){
                    self.wifi_password_TextField.text = model.wifiPasswordName;
                }
            }
            
        };
       [self.navigationController presentViewController:wifilist animated:YES completion:nil];
    }else{
     
       [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Failed to scan WiFi, please re-trigger the device to enter the distribution network mode", nil) duration:4];
    }
}


-(UITextField*)wifi_password_TextField
{
    if (!_wifi_password_TextField) {
         _wifi_password_TextField = [[UITextField alloc]init];
         _wifi_password_TextField.delegate = self;
         _wifi_password_TextField.textColor = [UIColor blackColor];
         _wifi_password_TextField.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
         _wifi_password_TextField.placeholder = NSLocalizedString(@"请输入网络密码", nil);
          NSMutableAttributedString *placeholderString = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"请输入网络密码", nil) attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:16]}];
                  _wifi_password_TextField.attributedPlaceholder = placeholderString;
         [self.view addSubview:_wifi_password_TextField];
        
        
         UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
        [btn addTarget:self action:@selector(wifi_password_TextFieldClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:@"vl0_form_show"] forState:UIControlStateNormal];
        _wifi_password_TextField.rightViewMode = UITextFieldViewModeAlways;
        _wifi_password_TextField.rightView = btn;
        
        [_wifi_password_TextField mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left).offset(28);
            make.right.equalTo(self.view.mas_right).offset(-28);
            make.top.equalTo(self.wifi_Name_TextField.mas_bottom).offset(33);
            make.height.mas_equalTo(44);
        }];

         _wifi_password_TextField.tag = 3456;
         _wifi_password_TextField.borderStyle = UITextBorderStyleNone;
         _wifi_password_TextField.leftViewMode = UITextFieldViewModeAlways;
         _wifi_password_TextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    }
    return _wifi_password_TextField;
    
}

- (void)wifi_password_TextFieldClick:(UIButton*)sender
{
    sender.selected = !sender.selected;
    _wifi_password_TextField.secureTextEntry = sender.selected;
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"vl0_form_hide"] forState:UIControlStateNormal];
    }else{
        [sender setImage:[UIImage imageNamed:@"vl0_form_show"] forState:UIControlStateNormal];
    }
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(90);
    }];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationBarHeight]);
    }];

    return YES;
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [self.selectedWiflLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(28);
        make.top.equalTo(self.view.mas_top).offset(50+[UIDevice dev_navigationBarHeight]);
    }];
}

-(UIButton*)nextButton
{
     if (!_nextButton) {
         _nextButton =[UIButton buttonWithType:UIButtonTypeCustom];
        [_nextButton addTarget:self action:@selector(nextButtonButtonBtnclick) forControlEvents:UIControlEventTouchUpInside];
         _nextButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:20.0];
         _nextButton.layer.cornerRadius = 25;
         _nextButton.layer.masksToBounds = YES;
        [self.view addSubview:_nextButton];
        [_nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(280);
            make.height.mas_equalTo(50);
            make.bottom.equalTo(self.view.mas_bottom).offset(-120);
            make.centerX.equalTo(self.view.mas_centerX);
        }];
    }
    
    return _nextButton;
}

- (void)nextButtonButtonBtnclick
{
    
     
    NSString *main_ip =   [[NSUserDefaults standardUserDefaults] objectForKey:@"main_ip"];
    NSString *sub_ip = [[NSUserDefaults standardUserDefaults] objectForKey:@"sub_ip"];
     
        NSLog(@"main_ip-->%@ sub_ip--%@",main_ip,sub_ip);
    

        NSTimeZone *zone =  [NSTimeZone systemTimeZone];
        NSInteger timeOff = [zone secondsFromGMT];
        NSInteger timeMin = timeOff/60;//相差分钟数
        NSInteger zone2 = timeMin/60;//相差时区
        NSLog(@"timeOff == %ld timeMin == %ld zone2 == %ld\n",timeOff,timeMin,zone2);
        NSString *timezone;
        if(timeMin % 60 == 0){
            
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld",(long)zone2];
            }else if(zone2 == 0){
                timezone = @"0";
            }else{
                timezone = [NSString stringWithFormat:@"%ld",(long)zone2];
            }
            
        }else{
        
            NSInteger zone3 = timeMin % 60;//相差分钟
            NSInteger zone2 = timeMin / 60;//相差小时
            
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld:%ld",(long)zone2,zone3];
            }else if(zone2 == 0){
                timezone = [NSString stringWithFormat:@"0:%ld",(long)zone3];
            }else{
                timezone = [NSString stringWithFormat:@"%ld:%ld",(long)zone2,zone3];
            }
        }

    
    if(self.wifi_Name_TextField.text.length > 0 && self.wifi_password_TextField.text.length > 0){

        
        if(self.bind_way == 1){
             
            if(self.is_support_screen && self.lock_id.length > 0){
                
                NSArray *listArray = [FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"xmCloudState"),bg_sqlValue(@(1))]];
                
                
                if(self.qrcode_way != 6 && listArray.count > 1){
                    
                    YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
                    wifilist.message_type = 1;
                    self.definesPresentationContext = YES;
                    wifilist.wifiarray = [NSArray arrayWithArray:listArray];
                    wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
                    wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                    wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
                        NSLog(@"选中返回的bid-->%@",wifi);
                        
                       
                        
                        [self add_bind_timer];
                    
                        NSData *data =  [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:wifi];
                        [self.blufiClient postCustomData:data];
                        
                    };
                   [self.navigationController presentViewController:wifilist animated:YES completion:nil];
                    
                }else{
                    
                    
                    
                    [self add_bind_timer];
                
                    NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                    [self.blufiClient postCustomData:data];
                    
                }
                
            }else{
                
              
                
                [self add_bind_timer];
               
                 NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                [self.blufiClient postCustomData:data];
            }

        }else{
            
            
            
            [self add_bind_timer];
            
            
            if(self.is_support_screen && self.lock_id.length > 0){
                
    
                //连接成功 接收数据
                [self.clientSocket readDataWithTimeout:-1 tag:0];

                NSData *data =   [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                [self.clientSocket writeData:data withTimeout:5 tag:20];
                
            
            }else{
            
                
                //连接成功 接收数据
                [self.clientSocket readDataWithTimeout:-1 tag:0];
                NSData *data =  [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                [self.clientSocket writeData:data withTimeout:5 tag:20];
                
            }
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(45 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 登录上
                [self login];
            });
        }
    }else{
        
        if(self.wifi_Name_TextField.text.length > 0){
      
            UIAlertController *alter = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"提示", nil) message:NSLocalizedString(@"确定家里的Wi-Fi密码为空", nil) preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *deleteButton = [UIAlertAction actionWithTitle:NSLocalizedString(@"确定", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
               
                

                
                if(self.bind_way == 1){
                
                    
                    if(self.is_support_screen && self.lock_id.length > 0){
                        
                        NSArray *listArray = [FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"xmCloudState"),bg_sqlValue(@(1))]];
                        
                        
                        if(self.qrcode_way != 6 && listArray.count > 1){
                            
                            YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
                            wifilist.message_type = 1;
                            self.definesPresentationContext = YES;
                            wifilist.wifiarray = [NSArray arrayWithArray:listArray];
                            wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
                            wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                            wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
                                NSLog(@"选中返回的bid-->%@",wifi);
                                
                                [self add_bind_timer];
                            
                                 NSData *data =  [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:wifi];
                                [self.blufiClient postCustomData:data];
                                
                            };
                           [self.navigationController presentViewController:wifilist animated:YES completion:nil];
                            
                        }else{
                            
                            
                            
                            [self add_bind_timer];
                           
                            NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:self.wifi_password_TextField.text main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                            [self.blufiClient postCustomData:data];
                            
                        }
                        
                    }else{
                        
                        [self add_bind_timer];
                        
                        NSData *data = [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:@"" main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                        [self.blufiClient postCustomData:data];
                    }
                    
                }else{
                   
                    [self add_bind_timer];
                    
                    [self.clientSocket readDataWithTimeout:-1 tag:0];
                    NSData *data =  [self bind_strWifi_name:self.wifi_Name_TextField.text wifi_pwd:@"" main_ip:main_ip sub_ip:sub_ip timezone:timezone strdns:SERVER_ADDRS is_screen:self.is_support_screen lock_id:self.lock_id];
                    [self.clientSocket writeData:data withTimeout:5 tag:20];
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        // 登录上
                        [self login];
                    });
                }
            }];
            [alter addAction:deleteButton];
            
            [self presentViewController:alter animated:YES completion:nil];
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"请输入WiFi名称", nil) duration:3];
        }
    }
}


- (NSData*)bind_strWifi_name:(NSString*)wifi_name  wifi_pwd:(NSString*)Wifi_pwd main_ip:(NSString*)main_ip sub_ip:(NSString*)sub_ip timezone:(NSString*)timezone strdns:(NSString*)strdns is_screen:(BOOL)is_screen  lock_id:(NSString*)lock_id
{
    
    AppDelegate *de = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    NSString *city =  de.cityName;
    NSLog(@"city --%@",city);
    
    NSData *data;
    
    //不同厂商的 server_type 类型不同
    // server_type : 2 琨山通用有限公司
    // server_type : 3 四川思维信息科技有限公司
    // server_type : 4 浪潮
    // server_type : 5 苏宁
    // server_type : 6 柯凌普
    // server_type : 7 维锐
   // int server_type = 2;
    /*
    if (is_screen && lock_id.length > 0) {
        
        {
            if(self.send_ip){
                //发送数据
                 NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"main_ip\":\"%@\",\"sub_ip\":\"%@\",\"lockid\":\"%@\",\"city\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,main_ip,sub_ip,lock_id,city,server_type];
                 NSLog(@"cusData ---- %@",cusData);
                 data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                
            }else{
                //发送数据
                 NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"lockid\":\"%@\",\"city\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,lock_id,city,server_type];
                 NSLog(@"cusData ---- %@",cusData);
                 data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
              
            }
        }
    }else{
        
        //该设备支持天气展示
        if (self.devicetype == EQUESVL4 || self.devicetype == EQUESVL5) {
            
                if(self.send_ip){
                    //发送数据
                     NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"main_ip\":\"%@\",\"sub_ip\":\"%@\",\"city\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,main_ip,sub_ip,city,server_type];
                     NSLog(@"cusData ---- %@",cusData);
                     data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                    
                }else{
                    //发送数据
                     NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"city\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,city,server_type];
                     NSLog(@"cusData ---- %@",cusData);
                     data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                  
                }
            
        }else{
            
                if(self.send_ip){
                    //发送数据
                     NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"main_ip\":\"%@\",\"sub_ip\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,main_ip,sub_ip,server_type];
                     NSLog(@"cusData ---- %@",cusData);
                     data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                    
                }else{
                    //发送数据
                     NSString *cusData = [NSString stringWithFormat:@"{\"ssid\":\"%@\",\"pwd\":\"%@\",\"user_name\":\"%@\",\"time_zone\":\"%@\",\"server_type\":%d}",wifi_name,Wifi_pwd,[Tooles getuserToken],timezone,server_type];
                     NSLog(@"cusData ---- %@",cusData);
                     data = [cusData dataUsingEncoding:NSUTF8StringEncoding];
                  
                }
            
        }
    }
    */
    
    YKIPinfo *appinfo = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
    
    
    // is_overseas 是否是海外 海外隐藏默认语音 isMainLand 1 代表是否是国内
    // thirdPartyId 客户品牌ID
    // colony 服务器集群信息id
    // colony_addr 服务器集群信息地址
    // ssid Wi-Fi名称
    // pwd Wi-Fi密码
    // time_zone 时区信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:wifi_name forKey:@"ssid"];
    [dict setValue:Wifi_pwd forKey:@"pwd"];
    [dict setValue:[Tooles getuserToken] forKey:@"user_name"];
    [dict setValue:timezone forKey:@"time_zone"];
    [dict setValue:@(![appinfo.isMainLand intValue]) forKey:@"is_overseas"]; //宠物配网是否是海外
    [dict setValue:@(ThirdPartyDemoBrand) forKey:@"thirdPartyId"];
    
    if (city.length > 0) {
        [dict setValue:city forKey:@"city"];
    }
    
    if(appinfo.mainip){
        [dict setValue:main_ip forKey:@"main_ip"];
        [dict setValue:sub_ip forKey:@"sub_ip"];
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    int colony = [[userDefaults objectForKey:@"colony"] intValue];
    NSString *colony_addr = [userDefaults objectForKey:@"colony_addr"];
  
    if (colony_addr.length  > 0) {
       [dict setValue:@(colony) forKey:@"colony"];
       if (colony > 5) {
          [dict setValue:colony_addr forKey:@"colony_addr"];
       }
    }
   // [dict setValue:@(server_type) forKey:@"server_type"];
    NSLog(@"dict ---- %@",dict);
    
    
    NSError *error;
    // 将字典转换为 JSON 数据
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    
    
    self.post_data = jsonData;
    return jsonData;
    
}


- (void)add_bind_timer
{
    [SVProgressHUD showWithStatus: NSLocalizedString(@"绑定设备中...", nil)];
    
    __block int timeout;
    if (self.bind_way == 1){
        if(self.devicetype == EQUESVL2){
            timeout = 45;
        }else{
            timeout = 30;
        }
    }else{
        timeout = 60;
    }
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _wait_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_wait_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_wait_timer, ^{
    
        timeout--;
        
        NSLog(@"bind devices timeout -->%d",timeout);
        
        //超时再发一遍配网信息
        if (self.bind_way == 1 && timeout == 20 && self.post_data.length > 0){
            [self.blufiClient postCustomData:self.post_data];
        }
        
        if (timeout <= 0) {
            
            if (_wait_timer) {
               dispatch_source_cancel(_wait_timer);
                _wait_timer = nil;
            }
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                if (self.bind_way == 1){
                  [self.espFBYBleHelper stopScan];
                   self.espFBYBleHelper = nil;
                }
                if([SVProgressHUD isVisible]){
                   [SVProgressHUD dismiss];
                }
                
                [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"绑定超时，请检查WiFi密码是否正确", nil) duration:3];
                
            }];
        }
    });
    dispatch_resume(_wait_timer);
}


- (NSArray *)jsonAnalysis:(id)message
{
    NSArray *results;
    NSString *strMsg = (NSString *)message;
    if (strMsg) {
        NSData *jsonData = [strMsg dataUsingEncoding:NSUTF8StringEncoding];
        results = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
        return results;
    }else{
        return results;
    }
}

#pragma mark 热点绑定
- (void)sendAP
{
    if (!self.clientSocket) {
         NSLog(@"开始创建 tcp service");
         self.clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
         NSError * error = nil;
        [self.clientSocket connectToHost:@"192.168.4.1" onPort:10001 error:&error];
    }
}


#pragma mark- GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"连接tcp服务成功 host -- >%@ port--->%d",host,port);
    self.clientSocket = sock;
    
    //连接成功 接收数据
    [self.clientSocket readDataWithTimeout:-1 tag:0];
    
    [self.clientSocket writeData:[[NSString stringWithFormat:@"{\"method\":\"wifilist\"}"] dataUsingEncoding:NSUTF8StringEncoding] withTimeout:5 tag:10];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    if(tag == 10){
        NSLog(@"获取Wi-Fi列表写数据成功");
    }else if (tag == 20){
        NSLog(@"发送配网数据写数据成功");
    }
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"连接出错-->%@",err);
}


- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    // 接收到回复数据处理
    NSString *receive = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"ap get message ---%@",receive);

    if (!receive) {
        receive = [[NSMutableString alloc]initWithData:[self cleanUTF8:data] encoding:NSUTF8StringEncoding];
        NSLog(@"cleanUTF8 str2-->%@ \n",receive);
    }
    
    
    if (!receive) {
        receive = [self convertedToUtf8String:data];
         NSLog(@"convertedToUtf8String str2-->%@ \n",receive);
    }
    
    
    NSDictionary *dict  = [Tooles jsonAnalysis:receive];
    
    /*
       {"count":25,"list":"[{\"ssid\":\"LINK_test\",\"rssi\":-31},{\"ssid\":\"Banker-WiFi\",\"rssi\":-36},{\"ssid\":\"TP-LINK_D5EE\",\"rssi\":-40},{\"ssid\":\"device-test\",\"rssi\":-42},{\"ssid\":\"999\",\"rssi\":-43},{\"ssid\":\"EQUES_UniFi\",\"rssi\":-44},{\"ssid\":\"HW2.4G\",\"rssi\":-45},{\"ssid\":\"\",\"rssi\":-46},{\"ssid\":\"lynlyn007\",\"rssi\":-46},{\"ssid\":\"ps\",\"rssi\":-48},{\"ssid\":\"UPGRADE-AP\",\"rssi\":-50},{\"ssid\":\"test007\",\"rssi\":-50},{\"ssid\":\"CU_n0rW\",\"rssi\":-56},{\"ssid\":\"test007\",\"rssi\":-57},{\"ssid\":\"NETGEAR35\",\"rssi\":-58},{\"ssid\":\"ChinaNet-39EP\",\"rssi\":-58},{\"ssid\":\"CL\",\"rssi\":-59},{\"ssid\":\"eques-home\",\"rssi\":-60},{\"ssid\":\"Xiaomi_D4BD\",\"rssi\":-62},{\"ssid\":\"ChinaNet-3m2z\",\"rssi\":-63},{\"ssid\":\"ChinaNet-iaJo\",\"rssi\":-64},{\"ssid\":\"789office\",\"rssi\":-75},{\"ssid\":\"CMCC-2f2N\",\"rssi\":-75},{\"ssid\":\"MERCURY_76A6\",\"rssi\":-56},{\"ssid\":\"USBServer_Setup\",\"rssi\":-69}]"}
     */
    if([receive containsString:@"eques_wifi_config"]){
     
        NSLog(@"绑定结果receive--%@",receive);
        
     //{"eques_wifi_config":{"describe":"e55bd61707105650205b02f004a254c5","status":0}}
        
        NSDictionary *dict = [Tooles jsonAnalysis:receive];
        /*
            Status（值 int 类型） Describe（string 类型）0 对应绑定成功的 32 位 bid
            1 未找到 WiFi
            2 WiFi 密码错误
            3 设备获取路由 IP 错误
            4 设备无法连接 WiFi
            5 设备登录失败
            6 设备绑定失败
            7 设备连接服务器失败
        */
        
        
        
        if (_wait_timer) {
           dispatch_source_cancel(_wait_timer);
            _wait_timer = nil;
        }
        
        NSDictionary *dict2 = [dict objectForKey:@"eques_wifi_config"];
        int code = [[dict2 objectForKey:@"status"] intValue];
        
        
        if(code != 0){
            if([SVProgressHUD isVisible]){
               [SVProgressHUD dismiss];
            }
        }
        
        
        NSString *title;
        NSString *subtitle;
        switch (code) {
            case 1:
            {
             title = NSLocalizedString(@"WiFi not found", nil);
             subtitle = NSLocalizedString(@"WiFi signal is bad, please enter correct WiFi name", nil);
            }
                break;
                
            case 2:
            {
                title = NSLocalizedString(@"WiFi password error", nil);
                subtitle = NSLocalizedString(@"Please enter the correct WiFi password", nil);
            }
                break;
            case 3:
            {
                title = NSLocalizedString(@"Device get route IP error", nil);
                subtitle = NSLocalizedString(@"WiFi connection error or device cannot connect to WiFi, please restart the router to try", nil);
                
            }
                break;
            case 4:
            {
                title = NSLocalizedString(@"The device cannot connect to WiFi", nil);
                subtitle = NSLocalizedString(@"Other exceptions encountered when connecting to WiFi, please restart the router to try", nil);
            }
                break;
            case 5:
            {
                title = NSLocalizedString(@"Device login failed", nil);;
                subtitle = @"";
            }
                break;
            case 6:
            {
                title = NSLocalizedString(@"Device binding failed", nil);
                subtitle = @"";
            }
                break;
            case 7:
            {
                title = NSLocalizedString(@"The device failed to connect to the server", nil);
                subtitle = NSLocalizedString(@"WiFi cannot connect to the internet. Please make sure WiFi can connect to the internet", nil);
            }
                break;
            default:
                break;
        }
        
       
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if(code != 0){
                self.failView = [[YKTipsView alloc]initwithTitle:title subtitle:subtitle];
                self.failView.delegate = self;
               [[UIApplication sharedApplication].keyWindow addSubview:self.failView];
               [self.failView show];
            }else{

                [self login];
                
                NSString *describe = [dict2 objectForKey:@"describe"];
                
                self.devicesid = describe;
                
                FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]),bg_sqlKey(@"bid"),bg_sqlValue(describe)]] firstObject];
                
                if(list){
                     if([SVProgressHUD isVisible]){
                        [SVProgressHUD dismiss];
                      }
                      [SVProgressHUD showSuccessWithStatus:@"绑定成功，当前用户已绑定该设备" duration:3];
                      [self.navigationController popToRootViewControllerAnimated:YES];
                    
                //创建数据模型
                }else{
                    
                    [self removeTimer];
             
                      FBDevicesList *list = [[FBDevicesList alloc]init];
                      list.bg_tableName = @"FBDevicesList";
                      list.userName = [Tooles getuserToken];
                      list.bid = describe;
                      list.role = self.devicetype;
                     [list bg_save];
                    
                    NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
                    
                    if(modelArray.count > 0){
                         FBWifiIModel *model = [modelArray firstObject];
                         model.wifiPasswordName = self.wifi_password_TextField.text;
                        [model bg_saveOrUpdate];
                    }else{
                         FBWifiIModel *model = [[FBWifiIModel alloc]init];
                         model.wifiName = self.wifi_Name_TextField.text;
                         model.wifiPasswordName = self.wifi_password_TextField.text;
                        [model bg_save];
                    }
                    
                     self.showSucessView = YES;
                    
                     BindSuccessViewController *vc = [[BindSuccessViewController alloc]init];
                     vc.delegate = self;
                     vc.optionstr = @"VL0";
                     vc.modalPresentationStyle = UIModalPresentationFullScreen;
                    [self.view.window.rootViewController presentViewController:vc animated:YES completion:^{
                    }];
                }
            }
        });
        return;
    }

    if([[dict objectForKey:@"count"] intValue] == 0){
        [SVProgressHUD showErrorWithStatus:@"设备搜索WiFi列表返回为空，请重新扫描设备屏幕二维码！" duration:3];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        return;
    }
    
    if([[dict objectForKey:@"count"] intValue] > 0){
        
        NSArray *strarray;
        if([receive containsString:@"\"[{"] && [receive containsString:@"}]\""]){
        
            NSString *no_format_str  = [dict objectForKey:@"list"];
            NSString *str1 = [no_format_str stringByReplacingOccurrencesOfString:@"[" withString:@""];
            NSString *str3 = [str1 stringByReplacingOccurrencesOfString:@"]" withString:@""];
            NSArray *Arrat = [str3 componentsSeparatedByString:@","];

            NSMutableArray *array = [NSMutableArray array];
            
            if(Arrat.count % 2 == 0 && Arrat.count > 0){
                for (int i = 1; i <= Arrat.count; i ++) {
                    if(i % 2 == 0){
                        NSString *str = [NSString stringWithFormat:@"%@,%@",Arrat[i-2],Arrat[i-1]];
                        NSData *jsonData = [str dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
                        [array addObject:responseJSON];
                    }
                }
                strarray = [NSArray arrayWithArray:array];
            }
        }else{
            strarray = [dict objectForKey:@"list"];
        }

        if(strarray.count){
            
            if (_timer) {
                dispatch_source_cancel(_timer);
                _timer = nil;
            }
            
            // 创建一个NSSortDescriptor对象，指定要排序的key为"age"
            NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"rssi" ascending:YES comparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                NSNumber *number1 = [NSNumber numberWithInteger:labs([(NSNumber *)obj1 integerValue])];
                NSNumber *number2 = [NSNumber numberWithInteger:labs([(NSNumber *)obj2 integerValue])];
                return [number1 compare:number2];
            }];

            // 使用sortDescriptor对数组进行排序
            NSArray *sortedArray = [strarray sortedArrayUsingDescriptors:@[sortDescriptor]];
            
            self.wifi_array = [NSArray arrayWithArray:sortedArray];
            
            NSLog(@"AP dict2 Wi-Fi-->%@",strarray);
            
            [SVProgressHUD dismiss];
            
            YKWiFiListVController *wifilist = [[YKWiFiListVController alloc] initWithType:kWHCustomAnimationTypePresent];
            self.definesPresentationContext = YES;
            wifilist.wifiarray = [NSArray arrayWithArray:sortedArray];
            wifilist.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.5];
            wifilist.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            wifilist.selectedBlock = ^(NSString * _Nonnull wifi) {
                NSLog(@"选中返回的Wi-Fi-->%@",wifi);
                self.wifi_Name_TextField.text = wifi;
                NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_Name_TextField.text)]];
                if(modelArray.count > 0){
                     FBWifiIModel *model = [modelArray firstObject];
                    if(model.wifiPasswordName.length > 0){
                        self.wifi_password_TextField.text = model.wifiPasswordName;
                    }
                }
            };
           [self.navigationController presentViewController:wifilist animated:YES completion:nil];
        }
    }
}

-  (void)login
{
    
    [self.clientSocket disconnect];
     self.clientSocket = nil;
     self.clientSocket.delegate = nil;
    
  
    __block int timeout = 30;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),5*NSEC_PER_SEC, 0); //每5秒执行
    dispatch_source_set_event_handler(_timer, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [YKBusinessFramework equesLogout];
            
            YKIPinfo *info = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
            [YKBusinessFramework loginWithUserName:info.user token:[Tooles getuserToken] appKey:ThirdPartyDemoAppKey server_adds:SERVER_ADDRS];
        });
        
        timeout--;

        if (timeout <= 0) {
            [self removeTimer];
        }
    });
    dispatch_resume(_timer);
   
    
}





/**
 剔除非UTF-8字符
 @param data 原来的数据data
 @return 处理后的输入data
 */
- (NSData *)cleanUTF8:(NSData *)data
{
    iconv_t cd = iconv_open("UTF-8", "UTF-8"); // 从UTF-8转UTF-8
    int one = 1;
    iconvctl(cd, ICONV_SET_DISCARD_ILSEQ, &one); // 剔除非UTF-8的字符

    size_t inbytesleft, outbytesleft;
    inbytesleft = outbytesleft = data.length;
    char *inbuf  = (char *)data.bytes;
    char *outbuf = malloc(sizeof(char) * data.length);
    char *outptr = outbuf;
    if (iconv(cd, &inbuf, &inbytesleft, &outptr, &outbytesleft)
        == (size_t)-1) {
        NSLog(@"this should not happen, seriously");
        return nil;
    }
    NSData *result = [NSData dataWithBytes:outbuf length:data.length - outbytesleft];
    iconv_close(cd);
    free(outbuf);
    return result;
}

-(NSString *)convertedToUtf8String:(NSData*)data{
    
    NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (string == nil) {
        string = [[NSString alloc] initWithData:[self UTF8Data:data] encoding:NSUTF8StringEncoding];
    }
    return string;
    
}

-(NSData *)UTF8Data:(NSData*)data{
    
    //保存结果
    NSMutableData *resData = [[NSMutableData alloc] initWithCapacity:data.length];
    
    NSData *replacement = [@"�" dataUsingEncoding:NSUTF8StringEncoding];
    
    uint64_t index = 0;
    const uint8_t *bytes = data.bytes;
    
    long dataLength = (long) data.length;
    
    while (index < dataLength) {
        uint8_t len = 0;
        uint8_t firstChar = bytes[index];
        
        // 1个字节
        if ((firstChar & 0x80) == 0 && (firstChar == 0x09 || firstChar == 0x0A || firstChar == 0x0D || (0x20 <= firstChar && firstChar <= 0x7E))) {
            len = 1;
        }
        // 2字节
        else if ((firstChar & 0xE0) == 0xC0 && (0xC2 <= firstChar && firstChar <= 0xDF)) {
            if (index + 1 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                if (0x80 <= secondChar && secondChar <= 0xBF) {
                    len = 2;
                }
            }
        }
        // 3字节
        else if ((firstChar & 0xF0) == 0xE0) {
            if (index + 2 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                uint8_t thirdChar = bytes[index + 2];
                
                if (firstChar == 0xE0 && (0xA0 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                } else if (((0xE1 <= firstChar && firstChar <= 0xEC) || firstChar == 0xEE || firstChar == 0xEF) && (0x80 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                } else if (firstChar == 0xED && (0x80 <= secondChar && secondChar <= 0x9F) && (0x80 <= thirdChar && thirdChar <= 0xBF)) {
                    len = 3;
                }
            }
        }
        // 4字节
        else if ((firstChar & 0xF8) == 0xF0) {
            if (index + 3 < dataLength) {
                uint8_t secondChar = bytes[index + 1];
                uint8_t thirdChar = bytes[index + 2];
                uint8_t fourthChar = bytes[index + 3];
                
                if (firstChar == 0xF0) {
                    if ((0x90 <= secondChar & secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                } else if ((0xF1 <= firstChar && firstChar <= 0xF3)) {
                    if ((0x80 <= secondChar && secondChar <= 0xBF) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                } else if (firstChar == 0xF3) {
                    if ((0x80 <= secondChar && secondChar <= 0x8F) && (0x80 <= thirdChar && thirdChar <= 0xBF) && (0x80 <= fourthChar && fourthChar <= 0xBF)) {
                        len = 4;
                    }
                }
            }
        }
        // 5个字节
        else if ((firstChar & 0xFC) == 0xF8) {
            len = 0;
        }
        // 6个字节
        else if ((firstChar & 0xFE) == 0xFC) {
            len = 0;
        }
        
        if (len == 0) {
            index++;
            [resData appendData:replacement];
        } else {
            [resData appendBytes:bytes + index length:len];
            index += len;
        }
    }
    
    return resData;
    
}



@end



